package com.xge.common_libary.view.utils

import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import me.drakeet.multitype.ItemViewBinder

abstract class BaseBindingBinder<T, VB : ViewBinding>(
    private val bindingInflater: (LayoutInflater, ViewGroup, Boolean) -> VB
) : ItemViewBinder<T, BindingViewHolder<T, VB>>() {

    override fun onCreateViewHolder(
        inflater: LayoutInflater, parent: ViewGroup
    ): BindingViewHolder<T, VB> {
        val binding = bindingInflater(inflater, parent, false)
        val holder = BindingViewHolder<T, VB>(binding)

        // 确保在主线程执行初始化
        if (Looper.myLooper() == Looper.getMainLooper()) {
            onViewHolderCreated(holder)
        } else {
            Handler(Looper.getMainLooper()).post {
                onViewHolderCreated(holder)
            }
        }

        return holder
    }

    override fun onBindViewHolder(holder: BindingViewHolder<T, VB>, item:T & Any, payloads: List<Any>) {
        holder.item = item
        super.onBindViewHolder(holder, item, payloads)
    }


    // 可选 override，用于初始化逻辑
    protected open fun onViewHolderCreated(holder: BindingViewHolder<T, VB>) {}
}
